﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using douyinVideoCodeAnimation.Service;
using redcatwf;

namespace douyinVideoCodeAnimation
{
    public partial class douyin_Main : Form
    {
        private RazorPainterWFCtl razorPainterWFCtl1;
        private Font myFont = new Font("黑体", 2f, FontStyle.Regular, GraphicsUnit.Point, 134);
        private Queue<string> queue = new Queue<string>();
        public douyin_Main()
        {
            InitializeComponent();
            razorPainterWFCtl1 = new redcatwf.RazorPainterWFCtl();
            razorPainterWFCtl1.Dock = System.Windows.Forms.DockStyle.Fill;
            razorPainterWFCtl1.Location = new System.Drawing.Point(0, 100);
            razorPainterWFCtl1.Name = "razorPainterWFCtl1";
            razorPainterWFCtl1.TabIndex = 0;
            panel1.Controls.Add(razorPainterWFCtl1);

        }

        private void VideoPlay_btn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(VideoPath_txtBox.Text))
            {
                MessageBox.Show("请先选择视频文件");
                return;
            }
            //开始处理视频文件
            string imgSavePath = ffMpegService.CatchImg(VideoPath_txtBox.Text);
            //开始提取音频
            string mp3SavePath = ffMpegService.CatchMp3(VideoPath_txtBox.Text);
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("正在截取视频图片...");
                Invoke(new Action(() =>
                {
                    VideoPlay_btn.Enabled = false;
                }));
                DateTime DqTime = DateTime.Now;
                //监听文件夹文件的创建
                FileSystemWatcher watcher = new FileSystemWatcher(imgSavePath, "*.*");
                watcher.Created += new FileSystemEventHandler((s, ee) =>
                {
                    DqTime = DateTime.Now;
                });
                watcher.EnableRaisingEvents = true;
                while (true)
                {
                    //当前时间超过5秒没有更新判断为视频文件图片全部截取完
                    if ((DateTime.Now - DqTime).Seconds > 4)
                    {
                        if (File.Exists(mp3SavePath))//音频文件已经提取完
                            break;
                    }
                    Thread.Sleep(1000);
                    Invoke(new Action(() =>
                    {
                        progressBar.Value++;
                        FileHandle_label.Text = progressBar.Value.ToString() + "% (正在截取视频帧)";
                    }));
                }
                Console.WriteLine("视频图片截取完成,正在准备灰化字符集合...");
                //视频图片全部截取完成,准备图片灰化
                var fileCount = Directory.GetFiles(imgSavePath).Count();
                int tempNum = progressBar.Value;
                for (int i = 1; i <= fileCount; i++)
                {
                    Bitmap bit = ReadImageFile(imgSavePath + "\\" + i + ".jpg");
                    queue.Enqueue(Generate(bit, 4, 2, 0));
                    Invoke(new Action(() =>
                    {
                        Console.WriteLine(i);
                        progressBar.Value = Convert.ToInt32(Convert.ToDouble(i) / Convert.ToDouble(fileCount) * (100 - tempNum)) + tempNum;
                        FileHandle_label.Text = progressBar.Value + "% (正在灰化视频帧)";
                    }));
                }
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        if (queue.Count > 0)
                        {
                            lock (razorPainterWFCtl1.RazorLock)
                            {
                                Console.WriteLine(queue.Count);
                                razorPainterWFCtl1.RazorGFX.Clear(SystemColors.Control);
                                razorPainterWFCtl1.RazorGFX.DrawString(queue.Dequeue(), myFont, Brushes.Black, 10f, 10f);
                                razorPainterWFCtl1.RazorPaint();
                            }
                        }
                    }
                });
                Thread.Sleep(1000);
                axWindowsMediaPlayer1.URL = mp3SavePath;
            });
        }
        private void ChoiceVideo_btn_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = false;//该值确定是否可以选择多个文件
            dialog.Title = "请选择视频文件";
            dialog.Filter = "所有文件(*.*)|*.*";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                VideoPath_txtBox.Text = dialog.FileName;
            }
        }
        public static string Generate(Bitmap bitmap, int rowSize, int colSize, int type)
        {
            StringBuilder result = new StringBuilder();
            //var charstr=" $@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'.";
            //char[] charset = charstr.ToArray();
            char[] charset = { ' ', '.', ',', ':', ';', 'i', '1', 'r', 's', '5', '3', 'A', 'H', '9', '8', '&', '@', '#' };
            if (type == 1)
            {
                //charset = new char[] { '8', '9', '6', '4', '3', '5', '7', '0', '2', '1', '.',' ' };
                charset = new char[] { ' ', '.', '1', '2', '0', '7', '5', '3', '4', '6', '9', '8' };
            }
            else if (type == 2)
            {
                charset = new char[] { '丶', '卜', '乙', '日', '瓦', '車', '馬', '龠', '齱', '龖' };
            }
            int bitmapH = bitmap.Height;
            int bitmapW = bitmap.Width;
            for (int h = 0; h < bitmapH / rowSize; h++)
            {
                int offsetY = h * rowSize;
                for (int w = 0; w < bitmapW / colSize; w++)
                {
                    int offsetX = w * colSize;
                    float averBright = 0;
                    for (int j = 0; j < rowSize; j++)
                    {
                        for (int i = 0; i < colSize; i++)
                        {
                            try
                            {
                                Color color = bitmap.GetPixel(offsetX + i, offsetY + j);
                                averBright += color.GetBrightness();
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                averBright += 0;
                            }
                        }
                    }
                    averBright /= (rowSize * colSize);
                    int index = (int)(averBright * charset.Length);
                    if (index == charset.Length)
                        index--;
                    result.Append(charset[charset.Length - 1 - index]);
                }
                result.Append("\r\n");
            }
            return result.ToString();
        }

        /// <summary>
        /// 通过FileStream 来打开文件，这样就可以实现不锁定Image文件，到时可以让多用户同时访问Image文件
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Bitmap ReadImageFile(string path)
        {
            FileStream fs = File.OpenRead(path); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            Bitmap bit = new Bitmap(result);
            return bit;
        }

       
    }
}
